/**
 * 
 */
package pers.vic.readlog.log.service;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import pers.vic.readlog.log.model.LogModel;
import pers.vic.readlog.log.util.LogWatchUtil;

/**
 * @author Vic.xu
 *
 */
@Service
public class LogService {

	/**
	 * 配置的文件夹
	 */
	@Value("${log.dirs}")
	private String dirs;
	
	public Set<String> dirSet = new HashSet<>();
	
	
	/**
	 * 配置的日志文件夹
	 */
	@PostConstruct
	public void post() {
		if (StringUtils.isNotBlank(dirs)) {
			String[] split = dirs.split(",");
			dirSet.addAll(Arrays.asList(split));
			dirSet.forEach(LogWatchUtil::init);
		}
	}
	
	
	public Set<String> dirSet(){
		return dirSet;
	}


	/**
	 * 读取文件夹下的日志文件
	 * @param dir 文件夹
	 */
	public List<LogModel> logs(String dir) {
		List<LogModel> list = new ArrayList<>();
		new File(dir).listFiles(new FileFilter() {
			@Override
			public boolean accept(File file) {
				String fileName = file.getName().toLowerCase();
				boolean enableFile = !file.isDirectory() && legalFile(fileName);
				if(enableFile) {
					LogModel log = new LogModel(file);
					list.add(log);
				}
				return false;
			}
		});
		//创建时间倒序
		list.sort((o1, o2)->o1.getUpdateDate() == o2.getUpdateDate() ? 0 :(o2.getUpdateDate().after(o1.getUpdateDate())? 1 : -1));
		return list;
		
	}
	
	// 合法的日志文件后缀
	public static boolean legalFile(String fileName) {
		return fileName.endsWith(".log") || fileName.endsWith(".txt")|| fileName.matches(".*?\\.log\\.\\d+$")|| fileName.matches(".*?\\.txt\\.\\d+$");
	}
	
	
}
